use std::collections::HashMap;

use model_graph_types::{
    container::workflow::{
        WorkflowDocumentReadeOptions, WorkflowDocumentReader, WorkflowEngine,
        WorkflowEngineCompileOptions, WorkflowEngineRunOptions,
    },
    modeling::{
        scheduler::{SchedulerTask, SchedulerTaskContentType, SchedulerTaskType},
        workflow::{WorkflowContentType, WorkflowEntity},
        Value,
    },
};
use tokio::runtime::Handle;

use crate::workflow::{SimpleWorkflowEngine, WorkflowDocumentJsonReader};

pub fn job_execute(task: &SchedulerTask) {
    tracing::debug!("job_execute:{}", task.identifier);
    if let Some(template) = &task.template {
        match template.task_type {
            SchedulerTaskType::Workflow => {
                match template.content_type {
                    SchedulerTaskContentType::Workflow => {
                        //
                        let handle = Handle::current();
                        if let Some(workflow) = &template.workflow {
                            let w = workflow.clone();
                            std::thread::spawn(move || {
                                handle.block_on(async {
                                    let result = execute_workflow(&w).await;
                                    match result {
                                        Ok(r) => {}
                                        Err(err) => {}
                                    }
                                });
                            });
                        }
                    }
                }
            }
            _ => {}
        }
    } else {
        tracing::debug!("没有查询到template");
    }
}

async fn execute_workflow(workflow: &WorkflowEntity) -> anyhow::Result<()> {
    tracing::debug!("execute_workflow:{}", workflow.identifier);

    let document = match workflow.content_type {
        WorkflowContentType::File => {
            WorkflowDocumentJsonReader::default()
                .read_from_json_file(&workflow.content, WorkflowDocumentReadeOptions::default())
                .await?
        }
        WorkflowContentType::String => {
            WorkflowDocumentJsonReader::default()
                .read_from_string(&workflow.content, WorkflowDocumentReadeOptions::default())
                .await?
        }
    };
    //
    let mut args = HashMap::new();

    args.insert(
        String::from("test"),
        Value::String(String::from("从长篇报告中提取洞察、识别风险并提炼关键信息")),
    );

    let res = SimpleWorkflowEngine::default()
        .fetch(
            document,
            args,
            WorkflowEngineCompileOptions::default(),
            WorkflowEngineRunOptions::default(),
        )
        .await;

    match res {
        Ok(response) => {
            tracing::debug!("{:?}", response);
        }
        Err(err) => {
            tracing::error!("{:?}", err);
        }
    }
    Ok(())
}
